import React, { useState, useEffect } from 'react';
import { Popup, PickerView, Input } from 'antd-mobile';
import { RightOutline } from 'antd-mobile-icons';
import regionData from 'china-area-data';
import './Bian.css';
import axios from 'axios';
import { useNavigate, useParams } from 'react-router-dom';

// 格式化地区数据（不变）
const formatRegionData = () => {
  const convertToOptions = (dataObj) => {
    return Object.entries(dataObj || {})
      .filter(([code, name]) => typeof code === 'string' && typeof name === 'string')
      .map(([code, name]) => ({ label: name, value: code }));
  };

  const provinces = convertToOptions(regionData['86']);
  const getCitiesByProvince = (provinceCode) => convertToOptions(regionData[provinceCode]);
  const getDistrictsByCity = (cityCode) => convertToOptions(regionData[cityCode]);

  return { provinces, getCitiesByProvince, getDistrictsByCity };
};

const { provinces, getCitiesByProvince, getDistrictsByCity } = formatRegionData();

const Bian = () => {
  const nav = useNavigate();
  const { id } = useParams();
  const isEditMode = !!id;
  
  // 表单状态（不变）
  const [recipient, setRecipient] = useState('');
  const [phone, setPhone] = useState('');
  const [detailAddress, setDetailAddress] = useState('');
  const [isDefault, setIsDefault] = useState(false);
  const [selectedProvince, setSelectedProvince] = useState('');
  const [selectedCity, setSelectedCity] = useState('');
  const [selectedDistrict, setSelectedDistrict] = useState('');
  const [regionText, setRegionText] = useState('');
  const [columns, setColumns] = useState([provinces, [], []]);
  const [visible1, setVisible1] = useState(false);
  const [loading, setLoading] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);

  // 初始化根字体（不变）
  useEffect(() => {
    const setRootFontSize = () => {
      document.documentElement.style.fontSize = '10px';
    };
    setRootFontSize();
    window.addEventListener('resize', setRootFontSize);
    return () => window.removeEventListener('resize', setRootFontSize);
  }, []);

  // 省市区联动逻辑（不变）
  useEffect(() => {
    const province = selectedProvince || '';
    if (!province) {
      setColumns([provinces, [], []]);
      setSelectedCity('');
      setSelectedDistrict('');
      return;
    }
    const cities = getCitiesByProvince(province);
    setColumns([provinces, cities, []]);
    if (!selectedCity && cities.length > 0) {
      setSelectedCity(cities[0].value || '');
    }
  }, [selectedProvince]);

  useEffect(() => {
    const city = selectedCity || '';
    if (!city) {
      setColumns(prev => [prev[0], prev[1], []]);
      setSelectedDistrict('');
      return;
    }
    const districts = getDistrictsByCity(city);
    setColumns(prev => [prev[0], prev[1], districts]);
    if (!selectedDistrict && districts.length > 0) {
      setSelectedDistrict(districts[0].value || '');
    }
  }, [selectedCity]);

  // 编辑模式加载数据（不变）
  useEffect(() => {
    if (!isEditMode) return;

    setLoading(true);
    const fetchAddressDetail = async () => {
      try {
        const response = await axios.get(`http://localhost:3010/di/getAddressById?_id=${id}`);
        
        if (response.data.code !== 200) {
          alert(`获取失败：${response.data.message || '未知错误'}`);
          nav('/di');
          return;
        }

        const address = response.data.data || {};
        setRecipient(address.recipient || '');
        setPhone(address.phone || '');
        setDetailAddress(address.detailAddress || '');
        setIsDefault(!!address.isDefault);
        setSelectedProvince(address.provinceCode || '');
        setSelectedCity(address.cityCode || '');
        setSelectedDistrict(address.districtCode || '');
        setRegionText(`${address.provinceName || ''}-${address.cityName || ''}-${address.districtName || ''}`);

      } catch (error) {
        console.error('加载地址失败:', error);
        alert(error.response?.status === 404 ? '接口不存在' : '加载失败，请重试');
      } finally {
        setLoading(false);
      }
    };

    fetchAddressDetail();
  }, [id, isEditMode, nav]);

  // 处理省市区选择（不变）
  const handlePickerChange = (values) => {
    const [province = '', city = '', district = ''] = values || [];
    setSelectedProvince(province);
    setSelectedCity(city);
    setSelectedDistrict(district);
    
    const provinceText = regionData['86'][province] || '';
    const cityText = regionData[province]?.[city] || '';
    const districtText = regionData[city]?.[district] || '';
    setRegionText([provinceText, cityText, districtText].filter(Boolean).join('-'));
  };

  // 表单验证（不变）
  const validateForm = () => {
    if (!recipient.trim()) {
      alert('请输入收件人姓名');
      return false;
    }
    if (!phone.trim()) {
      alert('请输入手机号码');
      return false;
    }
    if (!regionText) {
      alert('请选择所在地区');
      return false;
    }
    if (!detailAddress.trim()) {
      alert('请输入详细地址');
      return false;
    }
    return true;
  };

  // 点击保存按钮（不变）
  const handleSubmit = async () => {
    if (!validateForm()) return;
    if (isSubmitting) return;
    setIsSubmitting(true);

    try {
      const addressData = {
        _id: id,
        recipient,
        phone,
        provinceCode: selectedProvince,
        provinceName: regionData['86'][selectedProvince] || '',
        cityCode: selectedCity,
        cityName: regionData[selectedProvince]?.[selectedCity] || '',
        districtCode: selectedDistrict,
        districtName: regionData[selectedCity]?.[selectedDistrict] || '',
        detailAddress,
        isDefault,
        logId: sessionStorage.getItem('logid') || ''
      };

      const response = await axios.post(
        'http://localhost:3010/di/updateAddress',
        addressData
      );

      if (response.data.code === 200) {
        alert('保存成功！');
        nav('/di');
      } else {
        alert(`保存失败：${response.data.message || '未知错误'}`);
      }

    } catch (error) {
      console.error('保存失败:', error);
      alert('网络错误，请稍后重试');
    } finally {
      setIsSubmitting(false);
    }
  };

  // 返回地址列表页（不变）
  const goBack = () => {
    nav('/di');
  };

  return (
    <div style={{
      width: '100%',
      maxWidth: '50rem',
      margin: '0 auto',
      fontFamily: 'Arial, sans-serif',
      fontSize: '1.6rem'
    }}>
      {/* 头部（不变） */}
      <div style={{
        backgroundColor: '#e51c23',
        color: 'white',
        padding: '1rem',
        display: 'flex',
        alignItems: 'center'
      }}>
        <span 
          style={{ fontSize: '2rem', marginRight: '14rem', cursor: 'pointer' }} 
          onClick={goBack}
        >
          &lt;
        </span>
        <span style={{ margin: '0', fontWeight: "bold" }}>
          编辑地址
        </span>
      </div>

      {/* 加载状态（不变） */}
      {loading && (
        <div style={{ padding: '2rem', textAlign: 'center', color: '#666' }}>
          加载地址中...
        </div>
      )}

      {/* 表单区域（核心修改：Input 的 onChange 事件处理） */}
      {!loading && (
        <form style={{ padding: '2rem' }}>
          {/* 收件人输入框（修正 onChange） */}
          <div style={{ marginBottom: '2rem', display: "flex", alignItems: 'center' }}>
            <span style={{ fontWeight: 'bold', marginRight: "3rem" }}>收件人：</span>
            <Input
              placeholder='请输入收件人姓名'
              value={recipient}
              onChange={(val) => {
                const inputValue = val?.target?.value ?? val; // 关键修正
                setRecipient(inputValue);
              }}
              style={{ flex: 1 }}
            />
          </div>

          {/* 手机号码输入框（修正 onChange） */}
          <div style={{ marginBottom: '2rem', display: "flex", alignItems: 'center' }}>
            <span style={{ fontWeight: 'bold', marginRight: "1.4rem" }}>手机号码：</span>
            <Input
              placeholder='请输入手机号码'
              value={phone}
              onChange={(val) => {
                const inputValue = val?.target?.value ?? val; // 关键修正
                setPhone(inputValue);
              }}
              style={{ flex: 1 }}
            />
          </div>

          {/* 所在地区（不变） */}
          <div style={{ marginBottom: '2rem', display: "flex", alignItems: 'center' }}>
            <span style={{ fontWeight: 'bold', marginRight: "1.3rem" }}>所在地区：</span>
            <div style={{ flex: 1, display: 'flex', alignItems: 'center' }}>
              <Input
                placeholder='请选择'
                value={regionText}
                readOnly
                onClick={() => setVisible1(true)}
                style={{ flex: 1 }}
              />
              <div onClick={() => setVisible1(true)}>
                <RightOutline />
              </div>
            </div>
          </div>

          {/* 详细地址输入框（修正 onChange） */}
          <div style={{ marginBottom: '2rem', display: "flex", alignItems: 'center' }}>
            <span style={{ fontWeight: 'bold', marginRight: "1.3rem" }}>详细地址：</span>
            <Input
              placeholder='请填写详细地址'
              value={detailAddress}
              onChange={(val) => {
                const inputValue = val?.target?.value ?? val; // 关键修正
                setDetailAddress(inputValue);
              }}
              style={{ flex: 1 }}
            />
          </div>

          {/* 默认地址（不变） */}
          <div style={{ marginBottom: '2rem', display: 'flex', alignItems: 'center' }}>
            <input
              type="checkbox"
              id="default-address"
              style={{ marginRight: '0.8rem', width: '1.6rem', height: '1.6rem' }}
              checked={isDefault}
              onChange={(e) => setIsDefault(e.target.checked)}
            />
            <label htmlFor="default-address" style={{ fontSize: '1.6rem' }}>
              设为默认地址
            </label>
          </div>

          {/* 保存按钮（不变） */}
          <button
            type="button"
            style={{
              width: '100%',
              padding: '1rem',
              backgroundColor: '#e51c23',
              color: 'white',
              border: 'none',
              borderRadius: '0.4rem',
              cursor: 'pointer',
              fontSize: '1.6rem'
            }}
            onClick={handleSubmit}
            disabled={isSubmitting}
          >
            {isSubmitting ? '保存中...' : '保存'}
          </button>
        </form>
      )}

      {/* 省市区选择弹窗（不变） */}
      <Popup
        visible={visible1}
        onMaskClick={() => setVisible1(false)}
        onClose={() => setVisible1(false)}
        bodyStyle={{ height: '40vh' }}
      >
        <div style={{ display: 'flex', justifyContent: 'space-between', padding: '1rem' }}>
          <button onClick={() => setVisible1(false)}>取消</button>
          <button onClick={() => setVisible1(false)}>确定</button>
        </div>
        <PickerView
          columns={columns}
          value={[
            selectedProvince || '',
            selectedCity || '',
            selectedDistrict || ''
          ]}
          onChange={handlePickerChange}
          mouseWheel={true}
        />
      </Popup>
    </div>
  );
};

export default Bian;